using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using FinanceStats.Business;
using System.IO;

namespace FinanceStats
{
    public partial class Login : Form
    {
        private string userPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal).ToString() + "\\finance_user.srl";
        
        public Login()
        {
            InitializeComponent();
        }

        private void Login_Load(object sender, EventArgs e)
        {
            if (File.Exists(userPath))
            {
                LoadUser();
                this.checkBox1.Checked = true;
            }
        }

        private string username;
        private int userID;

        public string Username
        {
            get { return username; }
            set { username = value; }
        }
        public int UserID
        {
            get { return userID; }
            set { userID = value; }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Username = textBox1.Text;
            this.userID = DataManager.Instance.CheckLogin(textBox1.Text, textBox2.Text);
            if (userID != -1)
            {
                if (this.checkBox1.Checked)
                {
                    SaveUser();
                }
                else
                {
                    File.Delete(userPath);
                }

                this.DialogResult = DialogResult.OK;
            }
            else
            {
                this.label3.Text = "Incrorect usernae or password!";
            }
        }

        private void SaveUser()
        {
            using (StreamWriter sw = new StreamWriter(File.Open(userPath, FileMode.Create, FileAccess.Write)))
            {
                sw.WriteLine(this.textBox1.Text);
                sw.WriteLine(this.textBox2.Text);
                sw.Flush();
                sw.Close();
            }
        }

        private void LoadUser()
        {
            using (StreamReader sr = new StreamReader(File.Open(userPath, FileMode.Open, FileAccess.Read)))
            {
                this.textBox1.Text = sr.ReadLine();
                this.textBox2.Text = sr.ReadLine();
                sr.Close();
            }
        }
    }
}